package server.business.service.Impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import server.business.mapper.BloodSampleStateMapper;
import server.business.pojo.BloodSample;
import server.business.pojo.BloodSampleReview;
import server.business.pojo.BloodSampleState;
import server.business.service.BloodSampleReviewService;
import server.business.service.BloodSampleService;
import server.business.mapper.BloodSampleMapper;
import org.springframework.stereotype.Service;
import server.business.vo.Result;
import server.business.vo.ResultExpand;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
* @author Galaxy
* @description 针对表【blood_sample】的数据库操作Service实现
* @createDate 2022-11-08 12:46:24
*/
@Service("bloodSampleService")
public class BloodSampleServiceImpl extends ServiceImpl<BloodSampleMapper, BloodSample>
    implements BloodSampleService{

    @Autowired
    private BloodSampleMapper bloodSampleMapper;
    @Autowired
    private BloodSampleService bloodSampleService;
    @Autowired
    private BloodSampleStateMapper bloodSampleStateMapper;
    @Autowired
    private BloodSampleReviewService bloodSampleReviewService;

    public IPage<BloodSample> selectByPage(int currentPage, int pageSize){
        Page<BloodSample> page = new Page<>(currentPage,pageSize);
        IPage<BloodSample> sampleIpage = bloodSampleMapper.selectPage(page,null);
        return sampleIpage;
    }

    /**
     * 查询数据
     *
     * @return {@link List}<{@link BloodSample}>
     */
    public List<BloodSample> queryData(){
        List<BloodSample> list = bloodSampleService.list();
        return list;
    }


    /**
     * 删除通过id
     *
     * @param id id
     * @return {@link Result}
     */
    public Result deleteById(Integer id){
        boolean success = bloodSampleService.removeById(id);
        Result result = new Result();
        if(success) {
            result.setCode("200");
            result.setMsg("删除成功");
        }else{
            result.setCode("500");
            result.setMsg("删除是失败");
        }
        return result;
    }


    /**
     * 获取页面
     *
     * @param request  请求
     * @param response 响应
     * @return {@link ResultExpand}
     */
    public ResultExpand getPage(HttpServletRequest request, HttpServletResponse response){
        Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));
        IPage<BloodSample> samplePage = bloodSampleService.selectByPage(currentPage, pageSize);
        ResultExpand resultExpand = new ResultExpand("200", "成功", samplePage.getRecords(), currentPage, pageSize, samplePage.getTotal(), samplePage.getPages());
        response.setStatus(200);
        return resultExpand;
    }


    /**
     * 搜索示例
     *
     * @param request  请求
     * @param response 响应
     * @return {@link ResultExpand}
     */
    public ResultExpand searchSample(HttpServletRequest request, HttpServletResponse response){
        //前端获取的样本ID、状态、操作员、时间范围
        String number = request.getParameter("number");
        String bloodNumber = request.getParameter("bloodNumber");
        String state = request.getParameter("state");
        String operator = request.getParameter("operator");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));
        //创建分页对象
//        IPage<BloodSample> page = new Page<>(currentPage, pageSize);
        //创建查询条件
        QueryWrapper<BloodSample> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", 0);
        if (number != "")
            queryWrapper.like("number", number);
        if (bloodNumber != "")
            queryWrapper.like("blood_number", bloodNumber);
        if (state != "")
            queryWrapper.eq("state", state);
        if(operator != "")
            queryWrapper.eq("operator", operator);
        if(startTime != "")
            queryWrapper.ge("collect_time", startTime);
        if(endTime != "")
            queryWrapper.le("collect_time", endTime  + " 23:59:59");
        //查询数据库
//        sampleService.page(page, queryWrapper);
        IPage<BloodSample> page = bloodSampleMapper.selectBloodSamplePage(
                new Page<>(currentPage, pageSize),  queryWrapper
        );
        //返回的数据
        ResultExpand resultExpand = new ResultExpand();
        resultExpand.setCurrent(currentPage).setPageSize(pageSize).setTotal(page.getTotal()).setPages(page.getPages());
        resultExpand.setCode("200");
        resultExpand.setMsg("搜索成功");
        resultExpand.setData(page.getRecords());
        return resultExpand;
    }


    /**
     * 增加血液样本
     *
     * @param sampleData 样本数据
     * @return {@link Result}
     */
    @Transactional(rollbackFor = Exception.class)
    public Result addBloodSample(@RequestBody BloodSample sampleData) {
        //查找”在库“状态的code
        QueryWrapper<BloodSampleState> bloodSampleStateQueryWrapper = new QueryWrapper<>();
        bloodSampleStateQueryWrapper.eq("name", "在库");
        BloodSampleState bloodSampleState = bloodSampleStateMapper.selectOne(bloodSampleStateQueryWrapper);
        String stateCode = bloodSampleState.getCode();

        //在blood_sample_review表中增加操作记录
        BloodSampleReview bloodSampleReview = new BloodSampleReview();
        bloodSampleReview.setNumber(sampleData.getNumber());
        bloodSampleReview.setState(stateCode);
        bloodSampleReview.setOperateTime(new Date());
        //需要操作人信息---------------------------------------------------待完善
        boolean successSampleReview = bloodSampleReviewService.save(bloodSampleReview);

        sampleData.setCollectTime(new Date());
        sampleData.setGmtModified(new Date());

        Result result = new Result();
        boolean successSample = bloodSampleService.save(sampleData);
        //出错回退
        if (successSample == false || successSampleReview == false) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        result.setCode("200");
        result.setMsg("插入血液样本成功");
        return result;
    }


    /**
     * 收到样品
     *
     * @param sampleData 样本数据
     * @return {@link Result}
     */
    public Result receiveSample(@RequestBody BloodSample sampleData) {
        //查找”在库“状态的code
        QueryWrapper<BloodSampleState> bloodSampleStateQueryWrapper = new QueryWrapper<>();
        bloodSampleStateQueryWrapper.eq("name", "在库");
        BloodSampleState bloodSampleState = bloodSampleStateMapper.selectOne(bloodSampleStateQueryWrapper);
        String stateCode = bloodSampleState.getCode();

        Result result = new Result();
        sampleData.setState(stateCode);
        boolean success = bloodSampleService.updateById(sampleData);
        if(success) {
            result.setCode("200");
            result.setMsg("签收成功");
        }else{
            result.setCode("500");
            result.setMsg("签收失败");
        }
        return result;
    }


    /**
     * 出样品
     *
     * @param sampleData 样本数据
     * @return {@link Result}
     */
    public Result outSample(@RequestBody BloodSample sampleData){
        //查找”出库“状态的code
        QueryWrapper<BloodSampleState> bloodSampleStateQueryWrapper = new QueryWrapper<>();
        bloodSampleStateQueryWrapper.eq("name", "出库");
        BloodSampleState bloodSampleState = bloodSampleStateMapper.selectOne(bloodSampleStateQueryWrapper);
        String stateCode = bloodSampleState.getCode();

        //在blood_sample_review表中增加操作记录
        BloodSampleReview bloodSampleReview = new BloodSampleReview();
        bloodSampleReview.setNumber(sampleData.getNumber());
        bloodSampleReview.setState(stateCode);
        bloodSampleReview.setOperateTime(new Date());
        //需要操作人信息---------------------------------------------------待完善
        bloodSampleReviewService.save(bloodSampleReview);

        Result result = new Result();
        sampleData.setState(stateCode);
        boolean success = bloodSampleService.updateById(sampleData);
        if(success) {
            result.setCode("200");
            result.setMsg("出库成功");
        }else{
            result.setCode("500");
            result.setMsg("出库失败");
        }
        return result;
    }


    /**
     * 丢弃样品
     *
     * @param sampleData 样本数据
     * @return {@link Result}
     */
    public Result discardSample(@RequestBody BloodSample sampleData){
        //查找”废弃“状态的code
        QueryWrapper<BloodSampleState> bloodSampleStateQueryWrapper = new QueryWrapper<>();
        bloodSampleStateQueryWrapper.eq("name", "废弃");
        BloodSampleState bloodSampleState = bloodSampleStateMapper.selectOne(bloodSampleStateQueryWrapper);
        String stateCode = bloodSampleState.getCode();

        //在blood_sample_review表中增加操作记录
        BloodSampleReview bloodSampleReview = new BloodSampleReview();
        bloodSampleReview.setNumber(sampleData.getNumber());
        bloodSampleReview.setState(stateCode);
        bloodSampleReview.setOperateTime(new Date());
        //需要操作人信息---------------------------------------------------待完善
        bloodSampleReviewService.save(bloodSampleReview);

        Result result = new Result();
        sampleData.setState(stateCode);
        //更新状态
        boolean success = bloodSampleService.updateById(sampleData);
        //逻辑删除
        boolean successDelete  = bloodSampleService.removeById(sampleData);
        if(success && successDelete) {
            result.setCode("200");
            result.setMsg("遗弃成功");
        }else{
            result.setCode("500");
            result.setMsg("遗弃失败");
        }
        return result;
    }


    /**
     * 下载excel
     *
     * @param request  请求
     * @param response 响应
     */
    public void downloadExcel(HttpServletRequest request, HttpServletResponse response){
        //前端获取的样本ID、状态、操作员、时间范围
        String number = request.getParameter("number");
        String state = request.getParameter("state");
        String operator = request.getParameter("operator");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        try {
            String filename = "血液样本";
            String userAgent = request.getHeader("User-Agent");
            if(userAgent.contains("MSIE")||userAgent.contains("Trident")){
                filename = URLEncoder.encode(filename,"UTF-8");            }else {
                filename = new String(filename.getBytes("UTF-8"),"ISO-8859-1");
            }
            response.setContentType("application/json.ms-exce");
            response.setCharacterEncoding("utf-8");
            response.addHeader("Content-Disposition","filename = " + filename + ".xlsx");
            QueryWrapper<BloodSample> queryWrapper = new QueryWrapper<>();
            if (number != "" && number != null)
                queryWrapper.like("number", number);
            if (state != "" && state != null)
                queryWrapper.eq("state", state);
            if(operator != "" && operator != null)
                queryWrapper.eq("operator", operator);
            if(startTime != "" && startTime != null)
                queryWrapper.ge("collect_time", startTime);
            if(endTime != "" && endTime != null)
                queryWrapper.le("collect_time", endTime + " 23:59:59");
            List<BloodSample> SampleDataList = bloodSampleService.list(queryWrapper);
            EasyExcel.write(response.getOutputStream(),BloodSample.class).sheet("sheet").doWrite(SampleDataList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}




